package com.example.tobebigfe.jsbridge

import android.webkit.WebView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import org.json.JSONObject


class JSBridgeUI(val activity: WebActivity, webView: WebView) : BridgeModuleBase(webView) {

    override fun callFunc(func: String, callbackId: String, arg: JSONObject) {
        when (func) {
            "toast" -> toast(arg)
            "alert" -> alert(arg)
            "confirm" -> confirm(callbackId, arg)
        }
    }

    private fun toast(arg: JSONObject) {
        val message = arg.getString("message")
        Toast.makeText(activity, message, Toast.LENGTH_SHORT).show()
    }

    private fun alert(arg: JSONObject) {
        activity.runOnUiThread {
            AlertDialog.Builder(activity)
                .setTitle(arg.get("title") as String? ?: "提示")
                .setMessage(arg.get("message") as String? ?: "")
                .setPositiveButton(arg.get("button") as String? ?: "确定") { _, _ -> }
                .create()
                .show()
        }
    }

    private fun confirm(callbackId: String, arg: JSONObject) {
        val buttons = mutableListOf<String>()
        if (arg.has("buttons")) {
            val buttonArr = arg.getJSONArray("buttons")
            for (i in 0 until buttonArr.length()) {
                buttons.add(buttonArr.getString(i))
            }
        } else {
            buttons.add("取消")
            buttons.add("确定")
        }

        val message = arg.get("message") as String?

        activity.runOnUiThread {
            AlertDialog.Builder(activity)
                .setTitle(message)
                .setItems(buttons.toTypedArray()) { _, index ->
                    callback(callbackId, index)
                }
                .create()
                .show()
        }
    }
}